layui.use(['form','layer','laydate','table','laytpl'],function(){
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laydate = layui.laydate,
        laytpl = layui.laytpl,
        table = layui.table;

		Date.prototype.Format = function (fmt) { //author: meizz   
		    var o = {  
		        "M+": this.getMonth() + 1, //月份   
		        "d+": this.getDate(), //日   
		        "H+": this.getHours(), //小时   
		        "m+": this.getMinutes(), //分   
		        "s+": this.getSeconds(), //秒   
		        "q+": Math.floor((this.getMonth() + 3) / 3), //季度   
		        "S": this.getMilliseconds() //毫秒   
		    };  
		    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));  
		    for (var k in o)  
		    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));  
		    return fmt;  
		} 

      rendering ();
       function rendering(){
       	 $.ajax({ 
            type: "GET",
            headers: {
                token :  $.cookie('token')
            },
            url: api+"loms/mg/order/all",
            data: {
               pageSize:100,
               pageNum:1
            },
            success: function(result){
            	tableData = result.data.list;
			   //新闻列表
			    var tableIns = table.render({
			        elem: '#newsList',
			        data : tableData,
			        cellMinWidth : 95,
			        page : true,
			        height : "full-125",
			        limit : 20,
			        limits : [10,15,20,25],
			        id : "newsListTable",
			        cols : [[
			            {field: 'consignee', title: '收货人', align:'center'},
			            {field: 'phone', title: '手机号', align:'center'},
			            {field: 'originPrice', title: '原价', align:'center', width:60},
			            {field: 'totalPrice', title: '总价', align:'center', width:60},
			            {field: 'discountPrice', title: '优惠', align:'center', width:60},
			            {field: 'remark', title: '备注', align:'center'},
			            {field: 'status', title: '状态', align:'center', templet:function (row) {
                                if(row.status == 0){
                                    return "待付款";
                                } else if(row.status == 1){
                                    return "待接单";
                                } else if(row.status == 2){
                                    return "待派送";
                                } else if(row.status == 3){
                                    return "待送达";
                                } else {
                                    return "已完成";
                                }
                            }},
			            {field: 'address', title: '地址', width:150},
			            {field: 'bookTime', title: '期望到达时间', align:'center',templet:function(a){
			            	if(a.bookTime.toString().length == 10){a.bookTime = a.bookTime * 1000}
			                 return new Date(a.bookTime).Format("yyyy-MM-dd");
			            }},
			            {field: 'createTime', title: '下单时间', align:'center',templet:function(a){
			            	if(a.createTime.toString().length == 10){a.createTime = a.createTime * 1000}
			                 return new Date(a.createTime).Format("yyyy-MM-dd");
			            }},
			            {title: '操作', width:170, templet:function (a) {
								var result = "<a class=\"layui-btn layui-btn-xs\" lay-event=\"detail\">详情</a>\n" +
                                    "\t\t";
                                if(a.status == 0){
                                    result += "<a class=\"layui-btn layui-btn-xs\" href='javascript:;'>待付款</a>";
                                } else if(a.status == 1){
                                    result += "<a class=\"layui-btn layui-btn-xs\" lay-event='op' >接单</a>";
                                } else if(a.status == 2){
                                    result += "<a class=\"layui-btn layui-btn-xs\" lay-event='op' >派送</a>";
                                } else if(a.status == 3){
                                    result += "<a class=\"layui-btn layui-btn-xs\" lay-event='op' >送达</a>";
                                } else {
                                    result += "<a class=\"layui-btn layui-btn-xs\" href='javascript:;'>已完成</a>";
								}
								return result;
                            },fixed:"right",align:"center"}
			        ]]
			    });

                table.on('tool(newsList)', function(obj){
			        var layEvent = obj.event,
			            rowData = obj.data;
			        if(layEvent === 'edit'){ //编辑
			            editNews(rowData);
			        }else if(layEvent === 'detail'){
                        detailItem(rowData);
			        } else if(layEvent === 'op'){
                        op(obj.data);
					}
			    });
				function op(a) {
					var url;
					if(a.status == 0){
                        url = api+"loms/mg/order/update?id=" +a.id + "&status=2";
                    } else if(a.status == 1){
                        url = api+"loms/mg/order/update?id=" +a.id + "&status=3";
					} else if(a.status == 2){
                        url = api+"loms/mg/order/update?id=" +a.id + "&status=4";
					}else if(a.status == 3){
                        url = api+"loms/mg/order/update?id=" +a.id + "&status=5";
					}
                    $.ajax({
                        type: "POST",
                        headers: {
                            token :  $.cookie('token')
                        },
                        url: url,
                        success: function(result){
                            if(result.code == 1){
                                top.layer.msg("操作成功！！");
                                setTimeout(function(){
                                    location.reload();
                                },1000);
                            } else {
                                top.layer.msg(result.message);
                            }
                        }
                    });
                }
                function detailItem(row){
                    if(row.bookTime.toString().length == 10){row.bookTime = row.bookTime * 1000}
                    var index = layui.layer.open({
                        title : "订单详情",
                        type : 2,
                        content : "order-detail.html",
                        success : function(layero, index){
                            var body = layui.layer.getChildFrame('body', index);
                            if(row){
                                body.find(".consignee").val(row.consignee);
                                body.find(".phone").val(row.phone);
                                body.find(".originPrice").val(row.originPrice);
                                body.find(".totalPrice").val(row.totalPrice);
                                body.find(".discountPrice").val(row.discountPrice);
                                body.find(".remark").val(row.remark);

                                if(row.status == 0){
                                    body.find(".status").val("待付款");
                                } else if(row.status == 1){
                                    body.find(".status").val("待接单");
								} else if(row.status == 2){
                                    body.find(".status").val("待派送");
								} else if(row.status == 3){
                                    body.find(".status").val("待送达");
								} else {
                                    body.find(".status").val("已完成");
								}
                                body.find(".address").val(row.address);
                                body.find(".bookTime").val(new Date(row.bookTime).Format("yyyy-MM-dd HH:mm:ss"));

                                var msProducts = row.products;
                                if(msProducts.length > 0){
                                    var productList = "<thead><tr><th>美食名称</th><th>数量(个)</th><th>单价(￥)</th><th>总价(￥)</th></tr></thead><tbody>";
                                    for (var i = 0; i < msProducts.length; i++) {
                                        productList += "<tr>" + "<td>" + msProducts[i].name + "</td><td>" + msProducts[i].quantity + "</td><td>"
                                            + msProducts[i].unitPrice + "</td><td>" + msProducts[i].totalPrice + "</td></tr>";
                                    }
                                    productList += "</tbody>";
                                    body.find(".product-list-detail").append(productList);
								}
                                form.render();
                            }
                            setTimeout(function(){
                                layui.layer.tips('点击此处返回文章列表', '.layui-layer-setwin .layui-layer-close', {
                                    tips: 3
                                });
                            },500)
                        }
                    });
                    layui.layer.full(index);
                    //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
                    $(window).on("resize",function(){
                        layui.layer.full(index);
                    })
                };

          	    function editNews(edit){
			        var index = layui.layer.open({
			            title : "修改通知",
			            type : 2,
			            content : "notice-edit.html",
			            success : function(layero, index){
			                var body = layui.layer.getChildFrame('body', index);
			                if(edit){
			                	debugger
			                    body.find(".id").val(edit.id);
			                    body.find(".title").val(edit.title);
			                    body.find(".abstract").val(edit.abstractContent);
			                    body.find(".type-list input[value="+edit.type+"]").prop("checked","checked");
			                    body.find("#news_content").val(edit.content);
//			                    body.find(".type-list input[value="+edit.type+"]").prop("checked","checked");
//                              body.find("#news_content").val(edit.content);
			                    form.render();
			                }
			                setTimeout(function(){
			                    layui.layer.tips('点击此处返回文章列表', '.layui-layer-setwin .layui-layer-close', {
			                        tips: 3
			                    });
			                },500)
			            }
			        });
			        layui.layer.full(index);
			        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
			        $(window).on("resize",function(){
			            layui.layer.full(index);
			        })
			    }
                            	
            }
        });

       }
});